# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from .forms import UploadFileForm
from .models import Document
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.core.exceptions import ValidationError
# Create your views here.





def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST,request.FILES)
        if form.is_valid():
            newdoc = Document(docfile=request.FILES['file'])
            # newdoc.validate_file_extension()
            if not newdoc.docfile.name.endswith('.jpg'):
                form = UploadFileForm()
                documents = Document.objects.all()
                return render(request,'list.html',{'str':u'文件上传错误','form':form,'documents':documents})
            else:
                newdoc.save()
                return HttpResponseRedirect(reversed('upload_file'))

    else:
        form = UploadFileForm()
        documents = Document.objects.all()

        return render(request,'list.html',{'form':form,'documents':documents})


def list(request):
    documents = Document.objects.all()
    paginator = Paginator(documents,6)
    page = request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except:
        post_list = paginator.page(1)


    return render(request,'lists.html',{'posts':post_list})